package com.secsys.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import com.secsys.dto.Pager;
import com.secsys.dto.ResourceDTO;
import com.secsys.model.TbSysLog;
import com.secsys.model.TbSysResource;
import com.secsys.model.TbSysRoleResource;
import com.secsys.model.TbSysUser;
import com.secsys.service.impl.LogServiceImpl;
import com.secsys.service.impl.ResourceServiceImpl;
import com.secsys.service.impl.RoleResourceServiceImpl;
/**
 * @Description 资源管理控制器
 * @author LiusQ
 *
 */
public class ResourceAction extends BaseAction<ResourceDTO> {

	private ResourceServiceImpl resourceService;
	
	private RoleResourceServiceImpl roleResourceService;
	
	private LogServiceImpl logService;
	
	private ResourceDTO resourceDto;
	
	private List<ResourceDTO> resourceList;
	
	private Integer resourceId;
	
	private  Pager pager;
	
	 

	public Pager getPager() {
		return pager;
	}

	public void setPager(Pager pager) {
		this.pager = pager;
	}

	@Override
	public ResourceDTO getModel() {
		// TODO Auto-generated method stub
		
		if(resourceDto==null){
			resourceDto = new ResourceDTO();
		}
		return resourceDto;
	}
	
	/**
	 * 增加资源,并添加日志
	 * @return
	 */
	public String addResource(){
		System.out.println(resourceDto.getParentResource());
		System.out.println(resourceDto.getMenuName()+" " + resourceDto.getParentFlag() + " " + resourceDto.getParentResource() + resourceDto.getSequenceNum()+" "+resourceDto.getUri());
		String sequenceNumTest;//生成资源序号
		if("1".equals(resourceDto.getParentFlag())){
			List<ResourceDTO> resourceFatherList = resourceService.findFatherResource();
			if(resourceFatherList!=null && resourceFatherList.size()>0){
				ResourceDTO resourceTest = resourceFatherList.get(0);
				String sequenceNum = resourceTest.getSequenceNum();
				int sequenceFlag = Integer.parseInt(sequenceNum.substring(0,3));
				if(sequenceFlag<10){
					sequenceNumTest = "00" + String.valueOf(sequenceFlag+1)+"_";
				}else if(sequenceFlag>=10 && sequenceFlag<100){
					sequenceNumTest = "0" + String.valueOf(sequenceFlag+1)+"_";
				}else{
					sequenceNumTest = String.valueOf(sequenceFlag+1)+"_";
				}
				resourceDto.setSequenceNum(sequenceNumTest);
			}
		}else{
			List<TbSysResource> resourceListChild = resourceService.findChildByFather(resourceDto.getParentResource());
			if(resourceListChild!=null){
				if(resourceListChild.size()<10){
					sequenceNumTest = resourceDto.getParentResource() + "00" + String.valueOf(resourceListChild.size());
				}else{
					sequenceNumTest = resourceDto.getParentResource() + "0" + String.valueOf(resourceListChild.size());
				}
				resourceDto.setSequenceNum(sequenceNumTest);
			}
		}
		
		resourceService.addResource(resourceService.getBeanFromDto(resourceDto));
		TbSysLog sysLog = new TbSysLog();
		sysLog.setOperation("添加" + resourceDto.getMenuName() + " 资源。" );
		TbSysUser userDto = (TbSysUser)session.get("userDto");
		sysLog.setOperationer(userDto.getUserName());
		Date opTime = new Date(); 
		sysLog.setOpTime(opTime);
		TbSysResource resourceLog = resourceService.findTbSysResourceByMenuName(resourceDto.getMenuName());
		System.out.println(resourceLog);
		String remark = resourceLog.getId().toString();
		sysLog.setRemark(remark);
		sysLog.setLogFlag(0);
		List<String> operationList = new ArrayList<String>();
		operationList.add("添加" + resourceDto.getMenuName() + " 资源。" );
		operationList.add("修改" + resourceDto.getMenuName() + " 资源。" );
		operationList.add("删除" + resourceDto.getMenuName() + " 资源。");
		
		List<TbSysLog> logTest = logService.listInOperation(operationList);
		if(logTest!=null && logTest.size()>0){
			for(TbSysLog sysLogTest : logTest){
				sysLogTest.setLogFlag(3);
				logService.saveOrUpdate(sysLogTest);
			}
		}
		logService.addLog(sysLog);//插入日志
		request.put("successMsg", resourceDto.getMenuName() +" 资源添加成功");
		request.put("successUrl", "/OneSecSys/bbs/resource/resource_listResource.action");
		return "addSuccess";
	}
	
	/**
	 * 创建修改资源页面
	 * @return
	 */
	public String updateResourceUI(){
		
		resourceDto = resourceService.getDtoFromPojo(resourceService.findById(resourceId));
		return "updateResourceUI";
	}
	
	/**
	 * 修改资源,并添加日志
	 * @return
	 */
	public String updateResource(){
		TbSysResource resourceLog = resourceService.findById(resourceDto.getId());
		TbSysLog sysLog = new TbSysLog();
		sysLog.setOperation("修改" + resourceLog.getMenuName() + " 资源。" );
		TbSysUser userDto = (TbSysUser)session.get("userDto");
		sysLog.setOperationer(userDto.getUserName());
		Date opTime = new Date(); 
		sysLog.setOpTime(opTime);
		String remark = resourceLog.getId().toString()+","+resourceLog.getMenuName()+","+resourceLog.getSequenceNum()+","+resourceLog.getUri()+","+resourceLog.getParentFlag();
		sysLog.setRemark(remark);
		sysLog.setLogFlag(0);
		List<String> operationList = new ArrayList<String>();
		operationList.add("添加" + resourceLog.getMenuName() + " 资源。" );
		operationList.add("修改" + resourceLog.getMenuName() + " 资源。" );
		operationList.add("删除" + resourceLog.getMenuName() + " 资源。");
		
		List<TbSysLog> logTest = logService.listInOperation(operationList);
		if(logTest!=null && logTest.size()>0){
			for(TbSysLog sysLogTest : logTest){
				sysLogTest.setLogFlag(3);
				logService.saveOrUpdate(sysLogTest);
			}
		}
		logService.addLog(sysLog);//插入日志
		resourceService.saveOrUpdate(resourceService.getBeanFromDto(resourceDto));
		request.put("successMsg", "资源修改成功");
		request.put("successUrl", "/OneSecSys/bbs/resource/resource_listResource.action");
		return "updateSuccess";
	}
	
	/**
	 * 级联删除资源,并添加日志
	 * @return
	 */
	public String deleteResourceUI(){
		//start add log
		TbSysResource resourceLog = resourceService.findById(resourceId);
		TbSysLog sysLog = new TbSysLog();
		sysLog.setOperation("删除" + resourceLog.getMenuName() + " 资源。" );
		TbSysUser userDto = (TbSysUser)session.get("userDto");
		sysLog.setOperationer(userDto.getUserName());
		Date opTime = new Date(); 
		sysLog.setOpTime(opTime);
		StringBuffer remark = new StringBuffer();
		remark.append(resourceLog.getMenuName()+","+resourceLog.getSequenceNum()+","+resourceLog.getUri()+","+resourceLog.getParentFlag());
		remark.append(",");
		List<TbSysRoleResource> roleResourceListLog = roleResourceService.queryByResourceId(resourceId);
		List<String> operationList = new ArrayList<String>();
		if(roleResourceListLog!=null && roleResourceListLog.size()>0){
			for(TbSysRoleResource roleResourceLog : roleResourceListLog){
				remark.append(roleResourceLog.getTbSysRole().getId());
				remark.append(",");
				operationList.add("删除" + roleResourceLog.getTbSysRole().getRole() + " 角色的"  + roleResourceLog.getTbSysResource().getMenuName() +" 资源");
				operationList.add("为" + roleResourceLog.getTbSysRole().getRole() + " 角色添加"  + roleResourceLog.getTbSysResource().getMenuName() +" 资源。");
			}
		}
		sysLog.setRemark(remark.toString());
		sysLog.setLogFlag(0);
		operationList.add("添加" + resourceLog.getMenuName() + " 资源。" );
		operationList.add("修改" + resourceLog.getMenuName() + " 资源。" );
		operationList.add("删除" + resourceLog.getMenuName() + " 资源。");
		List<TbSysLog> logTest = logService.listInOperation(operationList);
		if(logTest!=null && logTest.size()>0){
			for(TbSysLog sysLogTest : logTest){
				sysLogTest.setLogFlag(3);
				logService.saveOrUpdate(sysLogTest);
			}
		}
		logService.addLog(sysLog);//插入日志
		//end add log
		//start delete resource
		resourceService.delete(resourceLog);		
		request.put("successMsg", "该资源已经删除成功");
		request.put("successUrl", "/OneSecSys/bbs/resource/resource_listResource.action");
		//end delete resource
		return "deleteSuccess";
	}
	
	/**
	 * 检查资源是否已经存在
	 * @return
	 * @throws Exception
	 */
	public String validateData() throws Exception{
		String menuName = new String(resourceDto.getMenuName().getBytes("iso8859-1"),"gbk");
		System.out.println("***********************"+ menuName);
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		PrintWriter out = ServletActionContext.getResponse().getWriter(); 
		StringBuffer validateMsg=null;
		if("".equals(menuName)){
			validateMsg = new StringBuffer("");
		}else{
			TbSysResource resourceTest = resourceService.findTbSysResourceByMenuName(menuName);
			if(resourceTest==null){	
				validateMsg = new StringBuffer("<font color='green'>ok</font>");		
			}else{
				validateMsg = new StringBuffer("<font color='red'> 资源已存在</font>");			
			}
		}
		
		out.print(validateMsg.toString());
		return null;
	}
	
	/**
	 * 检查资源是否已经存在(修改时)
	 * @return
	 * @throws Exception
	 */
	public String validateUpdateData()throws Exception{
		String menuName = new String(resourceDto.getMenuName().getBytes("iso8859-1"),"gbk");
		System.out.println("***********************"+ resourceDto.getId());
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		PrintWriter out = ServletActionContext.getResponse().getWriter(); 
		StringBuffer validateMsg=null;
		if("".equals(menuName)){
			validateMsg = new StringBuffer("");
		}else{
			TbSysResource resourceTest = resourceService.findTbSysResourceByMenuName(menuName,resourceDto.getId());
			if(resourceTest==null){	
				validateMsg = new StringBuffer("<font color='green'>ok</font>");		
			}else{
				validateMsg = new StringBuffer("<font color='red'> 资源已存在</font>");			
			}
		}
		
		out.print(validateMsg.toString());
		return null;
	}
	
	/**
	 * 如果parentFlag是0，则显示父级菜单，供用户选择
	 * @return
	 */
	public String validateFlag()throws Exception{
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		PrintWriter out = ServletActionContext.getResponse().getWriter(); 
		StringBuffer validateMsg=null;
		List<ResourceDTO> resourceFatherList = resourceService.findFatherResource();
		if(resourceFatherList!=null && resourceFatherList.size()>0){
			validateMsg = new StringBuffer("<table width='100%' border='0' cellpadding='0' cellspacing='0'> <tr height='30px'><td align='left' width='40%'>所属父级菜单：</td> <td align='left'><select name='resourceDto.parentResource' class='validate-selection'>");
			validateMsg.append("<option>请选择</option>");
			for(ResourceDTO resourceTest : resourceFatherList){
				validateMsg.append("<option value='"+ resourceTest.getSequenceNum() +  "'>"+ resourceTest.getMenuName() +"</option>");
			}
			validateMsg.append("</select></td></tr></table>");
		}
		out.print(validateMsg.toString());
		return null;
	}
	
	/**
	 * 查询资源列表
	 * @return
	 */
	public String listResource(){
		resourceList = resourceService.listResource();
		return "listResource";
	}

	public ResourceServiceImpl getResourceService() {
		return resourceService;
	}

	public void setResourceService(ResourceServiceImpl resourceService) {
		this.resourceService = resourceService;
	}

	public ResourceDTO getResourceDto() {
		return resourceDto;
	}

	public void setResourceDto(ResourceDTO resourceDto) {
		this.resourceDto = resourceDto;
	}

	public List<ResourceDTO> getResourceList() {
		return resourceList;
	}

	public void setResourceList(List<ResourceDTO> resourceList) {
		this.resourceList = resourceList;
	}

	public RoleResourceServiceImpl getRoleResourceService() {
		return roleResourceService;
	}

	public void setRoleResourceService(RoleResourceServiceImpl roleResourceService) {
		this.roleResourceService = roleResourceService;
	}

	public Integer getResourceId() {
		return resourceId;
	}

	public void setResourceId(Integer resourceId) {
		this.resourceId = resourceId;
	}

	public LogServiceImpl getLogService() {
		return logService;
	}

	public void setLogService(LogServiceImpl logService) {
		this.logService = logService;
	}

}
